<template>
  <div class="app-container calendar-list-container">
    <el-button class="filter-item" type="primary" @click="cancel">返回</el-button>
    <!-- <el-button class="filter-item" type="success" @click="addGoods">订单商品</el-button>
    <el-button class="filter-item" type="danger" @click="addStockGoods">添加商品</el-button>-->
    <el-button class="filter-item" type="primary" @click="quickDelete">作废</el-button>
    <!-- <el-button class="filter-item" type="success" @click="searchGoods('MB')">添加验布</el-button>
     <el-button class="filter-item" type="success" @click="searchGoods('DB')">添加底布</el-button>
    <el-button class="filter-item" type="success" @click="searchGoods('ORDER')">订单商品</el-button>-->
    <el-input placeholder="序列号" v-model="searchText" ref="searchText" class="input-box">
      <el-button slot="append" icon="el-icon-search" @click="searchGoods('BUSINESS')">搜索序列号</el-button>
    </el-input>
     <el-button class="filter-item" type="success" @click="searchGoods('BUSINESSGOODS')">添加验布</el-button>
    <el-button class="filter-item" type="primary" @click="save">提交</el-button>
    <div class="w-body">
      <el-form :model="entity" :rules="dataRule" ref="entity" label-width="80px" size="small">
        <el-row>
          <el-col :span="5">
            <el-form-item label="大货订单" prop="orderNo">
              <el-input v-model="entity.orderNo" :disabled="true">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="客户名称" prop="customerName">
              <el-input v-model="entity.customerName" :disabled="true">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="工序" prop="stepName">
              <el-input v-model="entity.stepName" :disabled="true">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="5">
            <el-form-item label="雇员" prop="employeeName">
              <el-input v-model="entity.employeeName">
                <el-button slot="append" icon="el-icon-search" @click="addOwner"></el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="加工单价" prop="price">
              <el-input v-model="entity.price" type="number" :disabled="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="外部单号" prop="outBusinessCode">
              <el-input v-model="entity.outBusinessCode">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="缸号">
              <el-input v-model="gangNo" type="text"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <div class="w-table">
              <grid gridTitle="物品信息" :url="recordUrl" :columns="columns" :loading="false" ref="mainGrid" height="auto" diffHeight="280" :pagination="false" @delete="doDelete"
                @print="doPrint" @printNumber="doPrintNumber" :permissions="permissions" :multi="false"></grid>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <!--弹出-->
    <div>
      <el-dialog title="商品输入" :visible.sync="dialogVisible" width="90%" @close="cancelWin">
        <div>
          <el-form :model="currentEntity" :rules="dataGoodsRule" ref="currentEntity" label-width="100px" size="small">
            <el-row>
              <el-col :span="3">
                <el-form-item label="">

                </el-form-item>
              </el-col>
              <el-col :span="18">
                <el-form-item label="">
                  <div style="height:100px;font-size:120px;color:green">
                    米数:{{currentEntity.realQuantity}}
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="3">
                <el-form-item label="">
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="物料名称" prop="materialName">
                  <el-input v-model="currentEntity.materialName" :readonly="true"> </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="色号" prop="modelName">
                  <el-input v-model="currentEntity.modelName" :readonly="true"> </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="门幅" prop="modelProp">
                  <el-input v-model="currentEntity.modelProp" :readonly="true"> </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="序列号" prop="serialNumber">
                  <el-input v-model="currentEntity.serialNumber" :readonly="true"> </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="单位" prop="unit">
                  <el-select v-model="currentEntity.unit" placeholder="单位">
                    <el-option v-for="(type,index) in unitList" :label="type.name" :value="type.value" :key="index"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="缸号" prop="gangNo">
                  <el-input v-model="currentEntity.gangNo"> </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="毛重" prop="goodsWeight">
                  <el-input v-model="currentEntity.goodsWeight" type="number" @change="weightChange"> </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="净重" prop="goodsNetWeight">
                  <el-input v-model="currentEntity.goodsNetWeight" type="number" :readonly="true"> </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="实际数量" prop="quantity">
                  <el-input v-model="currentEntity.quantity" type="number" :readonly="true"> </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="读取数量" prop="realQuantity">
                  <el-input v-model="currentEntity.realQuantity" type="number" @change="quantityChange">
                    <el-button slot="append" icon="el-icon-search" @click="readLength">读取</el-button>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="扣减数量" prop="deleteQuantity">
                  <el-input-number v-model="currentEntity.deleteQuantity" :precision="2" :step="0.1" @change="quantityChange" :max="0"></el-input-number>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <div class="error">
                  <span v-for="(item,index) in errorList" :key="index">
                    <el-button v-show="item.number>0" type="primary" v-for="(i,cindex) in item.number" :key="cindex" @click="addTag(item,i)">{{item.errorName}}
                      <span>({{i}})</span>
                    </el-button>
                    <el-button v-show="item.number==0" type="primary" @click="addTag(item,0)">{{item.errorName}}
                    </el-button>
                  </span>
                </div>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="备注" prop="remark">
                  <el-tag type="danger" class="errorTag" v-for="(item,index) in elTags" :key="index" closable @close="handleClose(item)">{{item.text}}</el-tag>
                  <el-input v-model="currentEntity.remark" type="textarea" :rows="10" :readonly="true"> </el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="cancelWin">取 消</el-button>
          <el-button type="primary" @click="saveInRecord">确 定</el-button>
        </span>
      </el-dialog>
    </div>
    <GridDialog ref="ownerGridDialog" :url="ownerUrl" :columns="userColunms" @select="selectOwnerData" :permissions="permissions" :queryEntity="{key: 'CUSTOMER'}" :multi="true"
      :selectSize="2">
    </GridDialog>
    <GridDialog ref="goodsGridDialog" :multi="true" :url="goodsUrl" :columns="goodsColumns" @select="selectGoodsData" :permissions="permissions" :queryEntity="goodsQueryEntity"
      :pagination="false"></GridDialog>
    <GridDialog ref="stockGridDialog" :multi="true" :url="stockGoodsUrl" :columns="goodsColumns" @select="selectGoodsData" :permissions="permissions"
      :queryEntity="goodsQueryEntity" :pagination="false" :queryList="modelQueryList"></GridDialog>
  </div>
</template>

<script>
import request from '@/router/axios'
import { Message, MessageBox } from 'element-ui'
import url from '@/const/apiURL'
import GridDialog from '@/components/GridDialog'
import grid from '@/components/Grid'
import { mapGetters } from 'vuex'
import { queryField } from '@/const/query'
import { colunms } from '@/const/colunms'
import { getLodop } from '@/const/lodop'
import { dict } from '@/const/dict'

export default {
  components: { GridDialog, grid },
  data () {
    return {
      gangNo: '',
      searchText: '',
      timer: null,
      errorList: [],
      unitList: dict().Unit,
      dialogVisible: false,
      recordUrl: url.BUSINESS_QUICK_IN_LIST_URL,
      ownerUrl: url.USER_LIST_URL,
      stockGoodsUrl: url.BUSINESS_GOODS_LIST_URL,
      goodsUrl: url.BUSINESS_IN_GOODS_LIST_URL,
      modelQueryList: queryField().modelName,
      userColunms: colunms().userColumns,
      goodsCode: '',
      template: null,
      currentEntity: {
        goodsWeight: null,
        goodsNetWeight: null,
        gangNo: null,
        quantity: 0,
        realQuantity: 0,
        deleteQuantity: 0,
        total: 1
      },
      entity: {
        customerCode: '',
        customerName: '',
        warehouseCode: '',
        employeeName: '',
        price: 0,
        goods: []
      },
      elTags: [],
      goodsQueryEntity: {},
      columns: [
        {
          label: '操作', width: 190, prop: 'btn', align: 'center', template: 'btn', opList: [{ name: '打印', clickName: 'print', auth: 'yes' }
            , { name: '打印序列号', clickName: 'printNumber', auth: 'yes' }]
        },
        { label: this.global.modelName, width: 80, prop: 'goodsName', align: 'center' },
        { label: this.global.modelProp, width: 70, prop: 'modelProp', align: 'center' },
        { label: '物料名称', minWidth: 100, prop: 'materialName', align: 'left' },
        // { label: '物料类型', width: 100, prop: 'materialTypeName', align: 'center' },
        { label: '单位', width: 60, prop: 'unit', align: 'center' },
        { label: '序列号', width: 120, prop: 'serialNumber', align: 'center' },
        { label: '数量', width: 80, prop: 'quantity', align: 'center' },
        { label: '扣减', width: 80, prop: 'deleteQuantity', align: 'center' },
        { label: '顺序', width: 60, prop: 'indexSort', align: 'center' },
        { label: '备注', width: 160, prop: 'remark', align: 'center' },
        {
          label: '操作', width: 90, prop: 'btn', align: 'center', template: 'btn', opList: [{ name: '删除', clickName: 'delete', auth: 'yes' }
          ]
        }
      ],
      goodsColumns: [
        { label: this.global.modelName, width: 100, prop: 'modelName', align: 'left' },
        { label: this.global.modelProp, width: 80, prop: 'modelProp', align: 'left' },
        { label: '物料名称', width: 160, prop: 'materialName', align: 'left' },
        { label: '物料类型', width: 80, prop: 'materialTypeName', align: 'center' },
        { label: '数量', width: 100, prop: 'quantity', align: 'center' },
        { label: '单位', width: 80, prop: 'unit', align: 'center' },
        { label: '序列号', width: 160, prop: 'serialNumber', align: 'center' },
        { label: '批次号', width: 160, prop: 'batchNo', align: 'center' }
      ],
      dataGoodsRule: {
        quantity: [{ required: true, message: '数量不能为空', trigger: 'blur' }]
      },
      dataRule: {
        // customerName: [{ required: true, message: '客户不能为空', trigger: 'blur' }],
        warehouseCode: [{ required: true, message: '仓库不能为空', trigger: 'blur' }],
        employeeName: [{ required: true, message: '雇员不能为空', trigger: 'blur' }]
      }
    }
  },
  mounted () {
    this.$refs.searchText.focus();
  },
  created () {
    this.paramsEntity = this.$route.query
    this.init()
  },
  computed: {
    ...mapGetters(['permissions'])
  },
  methods: {
    init () {
      this.initData()
      this.initLodop()
    },
    handleClose (tag) {
      this.elTags.splice(this.elTags.indexOf(tag), 1);
      this.currentEntity.deleteQuantity += tag.quantity
      let texts = []
      this.elTags.forEach(element => {
        texts.push(element.text)
      })
      this.currentEntity.remark = texts.join(";")
      this.quantityChange()
    },
    initLodop () {
      LODOP = getLodop()
      LODOP.PRINT_INIT('') //打印初始化
      LODOP.SET_PRINT_MODE("PROGRAM_CONTENT_BYVAR", true);
      LODOP.SET_PRINT_STYLE('FontSize', 18) //设置对象风格
      LODOP.SET_PRINT_STYLE('Bold', 1) ////设置对象风格
      LODOP.SET_PRINT_PAGESIZE(0, 2000, 2000, '') //设定纸张大小
      LODOP.SET_PRINT_MODE('PRINT_PAGE_PERCENT', '55%')//设置缩放
      LODOP.SET_PREVIEW_WINDOW(2, 2, 0, 0, 0, '')//设置窗口
    },
    initTemplate (orderNo) {
      this.templateOp(orderNo).then(data => {
        if (data) {
          this.template = data.template
        }
      })
    },
    templateOp (orderNo) {
      return request({
        url: url.ORDER_TEMPLATE_VIEW_URL,
        method: 'post',
        data: { 'key': 'key' },
        params: { 'orderNo': orderNo }
      })
    },
    cancel () {
      this.$router.go(-1)
    },
    addOwner () {
      this.$refs['ownerGridDialog'].show()
      this.elTags = []
    },
    selectOwnerData (rows) {
      this.entity.employee = rows[0].userCode
      this.entity.employeea = rows[1].userCode
      this.entity.employeeName = rows[0].userName + ',' + rows[1].userName
    },
    quantityChange () {
      this.$nextTick(() => {
        this.currentEntity.quantity = (Number(this.currentEntity.realQuantity) + Number(this.currentEntity.deleteQuantity)).toFixed(2)
      })
    },
    timeReadData () {
      this.timer = setInterval(this.readLength, 3500);
    },
    cancelWin () {
      this.dialogVisible = false
      clearInterval(this.timer)
    },
    readLength () {
      this.lengthUrl().then(data => {
        if (data) {
          this.currentEntity.realQuantity = Number(data || 0).toFixed(1)
          this.currentEntity.quantity = (Number(this.currentEntity.realQuantity) + Number(this.currentEntity.deleteQuantity)).toFixed(2)
        }
      })
      return true
    },
    weightChange () {
      this.currentEntity.goodsNetWeight = (Number(this.currentEntity.goodsWeight) - Number(this.currentEntity.weightDiff || 0)).toFixed(1)
    },
    addTag (item, quantity) {
      if (item.needLength) {
        this.lengthUrl().then(data => {
          if (data) {
            this.elTags.push({ text: data + '米-' + item.errorName + '(' + quantity + ')', quantity: item.deleteLength })
            let texts = []
            this.elTags.forEach(element => {
              texts.push(element.text)
            })
            this.currentEntity.remark = texts.join(";")
          }
        })
      } else {
        this.elTags.push({ text: item.errorName, quantity: item.deleteLength })
        let texts = []
        this.elTags.forEach(element => {
          texts.push(element.text)
        })
        this.currentEntity.remark = texts.join(";")
      }
      this.currentEntity.deleteQuantity -= Number(item.deleteLength)
      this.quantityChange()
    },
    saveInRecord () {
      clearInterval(this.timer);
      this.saveUrl(this.currentEntity).then((data) => {
        if (data) {
          this.dialogVisible = false
          this.$refs['mainGrid'].reload()
        }
      })
    },
    doPrintNumber (row) {
      eval(this.global.numberPrint)
      LODOP.SET_PRINT_STYLEA("序列号", "CONTENT", row.serialNumber);
      //打印
      //LODOP.PRINT()
      LODOP.PREVIEW()
    },
    doPrint (row) {
      if (this.template) {
        MessageBox.confirm('是否打印?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          eval(this.template)
          this.printUrl(row.code).then(data => {
            if (data) {
              data.forEach((item, index) => {
                LODOP.SET_PRINT_STYLEA(item.propertyName, "CONTENT", item.propertyValue);
              })
            }
            //LODOP.PRINT()
            //打印
            LODOP.PREVIEW()
          })
        })
      } else {
        MessageBox.alert("请先配置唛头");
      }
    },
    searchGoods (type) {
      this.elTags = []
      let params = this.paramsEntity
      params.type = type
      if (type == 'BUSINESS') {
        params.serialNumber = this.searchText
        this.loadGoods(params, true)
        this.searchText = null
      } else if (type == 'BUSINESSGOODS') {
        params.type = 'BUSINESS'
        params.serialNumber = null
        this.loadGoods(params, true)
      } else {
        this.loadGoods(params, false)
      }
    },
    loadGoods (params, isbusinsess) {
      this.timeReadData()
      this.viewGoodsUrl(params).then(data => {
        if (data) {
          this.dialogVisible = true
          this.currentEntity = data
          this.currentEntity.goodsCode = data.modelCode
          this.currentEntity.quickCode = this.entity.quickCode
          this.currentEntity.quantity = 0
          this.currentEntity.gangNo = this.entity.gangNo || this.gangNo
          this.currentEntity.deleteQuantity = 0
          this.currentEntity.total = 1
          if (isbusinsess) {
            this.currentEntity.code = data.code
            this.currentEntity.quantity = null
          }
        }
      })
    },
    addGoods () {
      this.$refs['goodsGridDialog'].show()
    },
    addStockGoods () {
      this.$nextTick(() => {
        this.$refs['stockGridDialog'].show()
      })
    },
    selectGoodsData (rows) {
      rows.forEach(row => {
        const rowData = {
          code: row.code,
          goodsCode: row.goodsCode || row.modelCode,
          goodsName: row.goodsName || row.modelName,
          modelName: row.goodsName,
          materialName: row.materialName,
          materialTypeName: row.materialTypeName,
          modelProp: row.modelProp,
          unit: row.unit,
          price: 0,
          outQuantity: row.quantity,
          gangNo: row, gangNo,
          batchNo: row.batchNo,
          serialNumber: row.serialNumber
        }
        this.$refs['mainGrid'].addRow(rowData)
      })
    },
    initStepPrice (customerCode, stepCode) {
      this.priceUrl({ customerCode, stepCode }).then(data => {
        if (data) {
          this.entity.price = data
        }
      })
    },
    save () {
      MessageBox.confirm('是否继续该操作, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$refs['entity'].validate((valid) => {
          if (valid) {
            this.submitUrl(this.entity).then(data => {
              if (data) {
                this.$router.go(-1)
              }
            })
          }
        })
      })
    },
    doDelete (row) {
      MessageBox.confirm('是否继续该操作, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteUrl(row.code).then((data) => {
          if (data) {
            this.$refs['mainGrid'].reload()
          }
        })
      })
    },
    quickDelete () {
      MessageBox.confirm('是否继续该操作, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.cancelUrl(this.entity.quickCode).then((data) => {
          if (data) {
            this.$router.go(-1)
          }
        })
      })
    },
    initData () {
      this.viewUrl(this.paramsEntity).then(data => {
        if (data) {
          this.entity = data
          this.goodsQueryEntity.orderNo = data.orderNo
          this.goodsQueryEntity.stepCode = data.stepCode
          this.goodsQueryEntity.goodsCode = data.goodsCode
          this.goodsQueryEntity.customerCode = data.customerCode
          this.$refs['mainGrid'].doQuery('', { quickCode: data.quickCode })
          this.initTemplate(data.orderNo)
          this.initStepPrice(data.customerCode, data.stepCode)
        }
      })
      this.errorUrl().then(data => {
        if (data) {
          this.errorList = data
        }
      })
    },
    viewUrl (data) {
      return request({
        url: url.BUSINESS_QUICK_VIEW_URL,
        method: 'post',
        data: data
      })
    },
    viewGoodsUrl (data) {
      return request({
        url: url.BUSINESS_QUICK_GOODS_URL,
        method: 'post',
        data: data
      })
    },
    lengthUrl () {
      return request({
        url: url.BUSINESS_QUICK_LENGTH_URL,
        method: 'post',
        data: { key: 'key' }
      })
    },
    priceUrl (data) {
      return request({
        url: url.CUSTOMER_PRICE_URL,
        method: 'post',
        data: data
      })
    },
    submitUrl (data) {
      return request({
        url: url.BUSINESS_QUICK_SUBMIT_URL,
        method: 'post',
        data: data
      })
    },
    cancelUrl (quickCode) {
      return request({
        url: url.BUSINESS_QUICK_DELETE_URL,
        method: 'post',
        data: { key: "key" },
        params: { quickCode }
      })
    },
    saveUrl (data) {
      return request({
        url: url.BUSINESS_QUICK_IN_ADD_URL,
        method: 'post',
        data: data
      })
    },
    deleteUrl (code) {
      return request({
        url: url.BUSINESS_QUICK_IN_DELETE_URL,
        method: 'post',
        data: { key: "key" },
        params: { code }
      })
    },
    printUrl (code) {
      return request({
        url: url.BUSINESS_QUICK_IN_PRINT_URL,
        method: 'post',
        data: { key: "key" },
        params: { code }
      })
    },
    errorUrl () {
      return request({
        url: url.ERROR_USABLE_URL,
        method: 'post',
        data: { key: "key" }
      })
    },
    warehouseUrl () {
      return request({
        url: url.WAREHOUSE_USABLE_URL,
        method: 'post',
        data: { key: 'key' }
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.w-body {
  padding-top: 8px;
}
.w-table {
  border: 1px solid #ebeef5;
}
.w-table-title {
  border: 1px solid #ebeef5;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: normal;
  word-break: break-all;
  line-height: 23px;
  display: inline-block;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  position: relative;
  vertical-align: middle;
  width: 100%;
  font-size: 14px;
  color: gray;
}
.errorTag {
  margin: 5px;
  font-size: 20px;
}
.error {
  margin: 5px;
}
.input-box {
  clear: both;
  width: 450px;
}
</style>
